/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.service.TreeService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.modules.sys.dao.AreaDao;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 区域Service
 * 
 * @author ThinkGem
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class AreaService extends TreeService<AreaDao, Area> {

	public List<Area> findAll() {
		return UserUtils.getAreaList();
	}

	@Transactional(readOnly = false)
	public void save(Area area) {
		super.save(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}

	@Transactional(readOnly = false)
	public void delete(Area area) {
		super.delete(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = false)
	public Map<String, Object> areajson(String uid) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Object areajson = CacheUtils.get("areajson");
			if (areajson != null) {
				result.put("data", (List<Map<String, Object>>) areajson);
				result.put("success", true);
				result.put("msg", "success");
				return result;
			}
			// 1.查询所有顶级
			List<Map<String, Object>> top = dao.topareajson(uid);
			List<Map<String, Object>> list = getAreaJson(top, uid);
			result.put("data", list);
			result.put("success", true);
			result.put("msg", "success");
			CacheUtils.put("areajson", list);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", false);
			result.put("msg", "faild");
			return result;
		}

	}

	// 递归算法查询子级
	public List<Map<String, Object>> getAreaJson(List<Map<String, Object>> list, String uid) {
		for (int i = 0; i < list.size(); i++) {
			List<Map<String, Object>> child = dao.childareajson((String) list.get(i).get("value"), uid);
			if (child.size() > 0) {
				list.get(i).put("children", child);
				getAreaJson(child, uid);
			}

		}
		return list;
	}

	public List<Map<String, Object>> findChildJson(String areaId) {

		return dao.findChildJson(areaId);
	}

}
